package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utlis.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Queue;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            // 生成随机数 验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            // 调用阿里云
            log.info("验证码为：{}", code);

            // 将生成的验证码保存起来Seesion
            session.setAttribute(phone, code);
            return Result.success("手机验证码已发送成功");
        }
        return Result.error("短信发送失败");
    }

    @Autowired
    private UserService userService;

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")  // 使用dto也可以， map也行
    public Result<User> login(@RequestBody Map map, HttpSession session) {
        // 获取手机号
        String phone = map.get("phone").toString();


        // 获取验证码
        String code = map.get("code").toString();

        // 从session中获取验证码比对
        Object sessionCode = session.getAttribute(phone);
        if (sessionCode != null && sessionCode.equals(code)) {
            // 还要比对，判断是否再数据库， 如果是新用户，还要偷偷的完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                // 说明是新用户
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return Result.success(user);
        }


        return Result.error("验证码不对!");
    }
}
